package com.jzo2o.foundations.job;

import com.jzo2o.api.foundations.dto.response.RegionSimpleResDTO;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.service.HomeService;
import com.jzo2o.foundations.service.IRegionService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * springCache缓存同步任务
 *
 **/
@Slf4j
@Component
public class SpringCacheSyncHandler {

    @Resource
    private IRegionService regionService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private HomeService homeService;

    /**
     * 已启用区域缓存更新
     * 每日凌晨1点执行
     */
    @XxlJob(value = "activeRegionCacheSync")
    public void activeRegionCacheSync() {
        log.info(">>>>>>>>开始进行缓存同步，更新已启用区域");
        //1.清理缓存
        String key = RedisConstants.CacheName.JZ_CACHE + "::ACTIVE_REGIONS";
        redisTemplate.delete(key);

        //2.刷新缓存
        List<RegionSimpleResDTO> regionList = regionService.queryActiveRegionListCache();
        //3.遍历区域列表
        for (RegionSimpleResDTO region : regionList) {
            String redisServeKey = RedisConstants.CacheName.SERVE_ICON + "::" + region.getId();

            //4.删除原有缓存数据
            redisTemplate.unlink(redisServeKey);

            //5.按照区域缓存服务列表
            homeService.firstPageServeList(region.getId());

            //服务类型的缓存key
            String redisServeTypeKey = RedisConstants.CacheName.SERVE_TYPE + "::" + region.getId();

            //6.删除原有的服务类型缓存列表
            redisTemplate.unlink(redisServeTypeKey);

            //7.按照区域缓存服务类型列表
            homeService.serveTypeList(region.getId());

            //热门服务的缓存key
            String redisHotServeKey = RedisConstants.CacheName.HOT_SERVE + "::" + region.getId();

            //8.删除原有的热门服务缓存列表
            redisTemplate.unlink(redisHotServeKey);

            //9.按照区域缓存热门服务列表
            homeService.hotServeList(region.getId());
        }



    }

}